"""
工具函数模块
提供通用的工具函数和辅助功能
"""

import hashlib
import uuid
import time
import re
from typing import Dict, Any, Optional, List
from datetime import datetime, timezone

# 性能监控工具
try:
    from .utils.performance import performance_monitor, timing_decorator, cache
except ImportError:
    # 如果导入失败，提供空实现
    performance_monitor = None
    timing_decorator = lambda name: lambda func: func
    cache = lambda func: func


def generate_id() -> str:
    """生成唯一ID"""
    return str(uuid.uuid4())


def generate_short_id(length: int = 8) -> str:
    """生成短ID"""
    return str(uuid.uuid4()).replace('-', '')[:length]


def get_current_timestamp() -> float:
    """获取当前时间戳"""
    return time.time()


def format_timestamp(timestamp: float, format_str: str = "%Y-%m-%d %H:%M:%S") -> str:
    """格式化时间戳"""
    dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
    return dt.strftime(format_str)


def calculate_checksum(data: bytes) -> str:
    """计算数据的MD5校验和"""
    return hashlib.md5(data).hexdigest()


def calculate_file_checksum(file_path: str) -> str:
    """计算文件的MD5校验和"""
    hash_md5 = hashlib.md5()
    try:
        with open(file_path, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        return hash_md5.hexdigest()
    except Exception:
        return ""


def validate_url(url: str) -> bool:
    """验证URL格式"""
    url_pattern = re.compile(
        r'^https?://'  # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|'  # domain...
        r'localhost|'  # localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
        r'(?::\d+)?'  # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)
    return url_pattern.match(url) is not None


def validate_email(email: str) -> bool:
    """验证邮箱格式"""
    email_pattern = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
    return email_pattern.match(email) is not None


def sanitize_filename(filename: str) -> str:
    """清理文件名，移除不安全字符"""
    # 移除路径分隔符和其他不安全字符
    unsafe_chars = ['/', '\\', ':', '*', '?', '"', '<', '>', '|']
    for char in unsafe_chars:
        filename = filename.replace(char, '_')
    return filename


def format_file_size(size_bytes: int) -> str:
    """格式化文件大小"""
    if size_bytes == 0:
        return "0B"
    
    size_names = ["B", "KB", "MB", "GB", "TB"]
    i = 0
    while size_bytes >= 1024 and i < len(size_names) - 1:
        size_bytes /= 1024.0
        i += 1
    
    return f"{size_bytes:.1f}{size_names[i]}"


def parse_version(version: str) -> tuple:
    """解析版本号为元组，用于版本比较"""
    try:
        parts = version.split('.')
        return tuple(int(part) for part in parts)
    except (ValueError, AttributeError):
        return (0, 0, 0)


def compare_versions(version1: str, version2: str) -> int:
    """比较版本号
    返回值：
    -1: version1 < version2
     0: version1 == version2
     1: version1 > version2
    """
    v1 = parse_version(version1)
    v2 = parse_version(version2)
    
    if v1 < v2:
        return -1
    elif v1 > v2:
        return 1
    else:
        return 0


def merge_dicts(dict1: Dict[str, Any], dict2: Dict[str, Any]) -> Dict[str, Any]:
    """深度合并字典"""
    result = dict1.copy()
    
    for key, value in dict2.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = merge_dicts(result[key], value)
        else:
            result[key] = value
            
    return result


def filter_dict(data: Dict[str, Any], allowed_keys: List[str]) -> Dict[str, Any]:
    """过滤字典，只保留允许的键"""
    return {k: v for k, v in data.items() if k in allowed_keys}


def safe_get(data: Dict[str, Any], key: str, default: Any = None) -> Any:
    """安全获取字典值，支持嵌套键"""
    keys = key.split('.')
    current = data
    
    for k in keys:
        if isinstance(current, dict) and k in current:
            current = current[k]
        else:
            return default
            
    return current


def retry_on_exception(max_retries: int = 3, delay: float = 1.0):
    """重试装饰器"""
    import asyncio

    def decorator(func):
        async def wrapper(*args, **kwargs):
            last_exception = None

            for attempt in range(max_retries):
                try:
                    return await func(*args, **kwargs)
                except Exception as e:
                    last_exception = e
                    if attempt < max_retries - 1:
                        await asyncio.sleep(delay * (2 ** attempt))  # 指数退避

            raise last_exception
        return wrapper
    return decorator


class RateLimiter:
    """简单的速率限制器"""
    
    def __init__(self, max_requests: int, time_window: float):
        self.max_requests = max_requests
        self.time_window = time_window
        self.requests = []
        
    def is_allowed(self) -> bool:
        """检查是否允许请求"""
        now = time.time()
        
        # 清理过期的请求记录
        self.requests = [req_time for req_time in self.requests 
                        if now - req_time < self.time_window]
        
        # 检查是否超过限制
        if len(self.requests) >= self.max_requests:
            return False
            
        # 记录当前请求
        self.requests.append(now)
        return True
